package com.jiangchuang.config;

import com.alibaba.fastjson2.JSONObject;
import com.jiangchuang.domain.Result;
import com.jiangchuang.domain.entity.User;
import com.jiangchuang.domain.entity.UserAdmin;
import com.jiangchuang.mapper.UserAdminMapper;
import com.jiangchuang.utils.JwtUtils;
import com.jiangchuang.utils.UserContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author jmk
 * token 拦截器 权限验证
 */
@Component
public class TokenIntercepter implements HandlerInterceptor {

    public final static String TOKEN_KEY = "token";

    @Autowired
    private UserAdminMapper adminMapper;

    /**
     * 预处理 controller方法执行前
     * @param request
     * @param response
     * @param handler
     * @return true：放行，执行下一个拦截器。如果没有，执行controller中方法
     *         false：不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //如果是OPTIONS请求 直接放行
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return  true;
        }
        // 从请求头中获取token
        String token = request.getHeader(TOKEN_KEY);

        if(StringUtils.isBlank(token)||!JwtUtils.isValidToken(token)){
            Result<Object> fail = Result.fail("身份信息失效，请重新登录.");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(fail));
            return false;
        }

        // 用户上下文设置用户信息
        String userId = JwtUtils.getUserId(token);
        UserAdmin user = adminMapper.selectById(userId);
        UserContextUtils.setCurrentUser(user);
        return true;
    }

    /**
     * controller方法执行后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

}